package com.corpgovernment.organization.mq;

import com.corpgovernment.common.mq.consumer.AbstractMultiTenantRocketMQConsumer;
import com.corpgovernment.common.mq.enums.MessageBizTypeEnum;
import com.corpgovernment.organization.Bo.EmployeeOpenCardMQBo;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.model.OpenCardEmployeeModel;
import com.corpgovernment.organization.service.CtripOpenCardService;
import com.corpgovernment.organization.service.IOrganizationEmployeeService;
import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Component
@Slf4j
public class EmployeeOpenCardMQConsumer extends AbstractMultiTenantRocketMQConsumer {

    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private CtripOpenCardService ctripOpenCardService;

    @Override
    protected void consume(MessageExt messageExt, ConsumeConcurrentlyContext context) {
        String msg = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        log.info("EmployeeOpenCardMQConsumer消费的消息:{}", msg);
        if (StringUtils.isBlank(msg)){
            log.error("员工开发收到的消息为空");
            return;
        }
        EmployeeOpenCardMQBo employeeOpenCard = JsonUtils.parse(msg, EmployeeOpenCardMQBo.class);
        log.info("employeeOpenCard:{}", JsonUtils.toJsonString(employeeOpenCard));
        process(employeeOpenCard);
    }

    /**
     * 任务执行
     * @return
     */
    public boolean process(EmployeeOpenCardMQBo employeeOpenCard){
        log.info("employeeOpenCard:{}", JsonUtils.toJsonString(employeeOpenCard));
        StringBuilder logContext = new StringBuilder();
        try {
            MbOrgEmployeeInfo employeeInfo = organizationEmployeeService.findByUid(employeeOpenCard.getUid());
            employeeInfo = Optional.ofNullable(employeeInfo).orElse(compensateGetEmployee(employeeOpenCard.getUid()));
            log.info("employeeInfo:{}", JsonUtils.toJsonString(employeeOpenCard));
            if (Objects.isNull(employeeInfo)){
                return false;
            }

            // 当前租户法人公司是否同步
            Boolean corporateEntityFlag = ctripOpenCardService.getCorporateEntitySyncFlag();

            OpenCardEmployeeModel model = convertOpenCardEmployee(employeeInfo, corporateEntityFlag);
            log.info("OpenCardEmployeeModel:{}", JsonUtils.toJsonString(employeeOpenCard));
            List<OpenCardEmployeeModel> failedList = ctripOpenCardService.openCard(employeeOpenCard.getOrgId(), Collections.singletonList(model), null);
            if (CollectionUtils.isNotEmpty(failedList)){
                return false;
            }
            return true;
        }catch (Exception e){
            log.error("员工开卡异常：{}", e);
        }finally {
            log.info("{}", logContext);
        }
        return false;
    }

    private static OpenCardEmployeeModel convertOpenCardEmployee(MbOrgEmployeeInfo employeeInfo, Boolean corporateEntityFlag) {
        OpenCardEmployeeModel model = new OpenCardEmployeeModel();
        model.setAreaCode(employeeInfo.getAreaCode());
        model.setEmail(employeeInfo.getEmail());
        model.setName(employeeInfo.getName());
        model.setGender(employeeInfo.getGender());
        model.setNationality(employeeInfo.getNationality());
        model.setBirthday(employeeInfo.getBirthday());
        model.setUid(employeeInfo.getUid());
        model.setMobilePhone(employeeInfo.getMobilePhone());
        if(corporateEntityFlag) {
            model.setCorporateEntity(employeeInfo.getCorporateEntity());
        }
        return model;
    }

    /**
     * 避免事物未提交问题-先睡眠 后查询未查到则无需处理
     * @param uid
     * @return
     * @throws InterruptedException
     */
    public MbOrgEmployeeInfo compensateGetEmployee(String uid) throws InterruptedException {
        Thread.sleep(2000);
        log.info("compensateGetEmployee");
        return organizationEmployeeService.findByUid(uid);
    }


    /**
     * 获取拼接卡号
     * @param prefix
     * @param uid
     * @return
     */
    public String getOpenCardUid(String prefix, String uid){
        return String.format("%s_%s_%s", prefix, TenantContext.getTenantId(), uid);
    }

    @Override
    protected MessageBizTypeEnum getMessageBizType() {
        return MessageBizTypeEnum.EMPLOYEE_OPEN_CARD;
    }
}
